from typing import Dict, Any
import logging
from rule_engine.position_limits import PositionLimiter
from rule_engine.volatility_control import VolatilityMonitor, DrawdownController
from src.data_agent.core.data_agent import DataAgent

logger = logging.getLogger(__name__)

class RiskAgent:
    """风控智能体核心类"""
    
    def __init__(self, config: Dict):
        self.data_agent = DataAgent()
        self.position_limiter = PositionLimiter(config['position_rules'])
        self.vol_monitor = VolatilityMonitor(config['volatility_rules'])
        self.drawdown_ctrl = DrawdownController(config['max_drawdown'])
        
        # 初始化风控规则引擎
        self.rule_engines = [
            self.position_limiter,
            self.vol_monitor,
            self.drawdown_ctrl
        ]
        
    async def pre_check_order(self, order: Dict) -> Dict:
        """订单预检"""
        portfolio = await self.data_agent.get_portfolio()
        market_data = await self.data_agent.get_market_data(order['symbol'])
        
        checks = {}
        for engine in self.rule_engines:
            if isinstance(engine, PositionLimiter):
                checks['position'] = engine.check_order(order, portfolio)
            elif isinstance(engine, VolatilityMonitor):
                checks['volatility'] = engine.update_and_check(
                    order['symbol'], market_data['price'])
                    
        return {
            "order_id": order['id'],
            "passed": all(checks.values()),
            "details": checks
        }
        
    async def realtime_monitoring(self):
        """实时风险监控"""
        while True:
            portfolio = await self.data_agent.get_portfolio()
            if self.drawdown_ctrl.update(portfolio['value']):
                logger.error("触发最大回撤限制!")
                await self.trigger_circuit_breaker()
                
    async def trigger_circuit_breaker(self):
        """触发熔断机制"""
        # 通知所有相关系统暂停交易
        await self.data_agent.broadcast_event("RISK_ALERT", {"action": "suspend"})